package com.itheima.stargraph.config;

import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Comfyui配置类
 *
 * @Author mr.Candy
 * @Date 2025/6/815:07
 */
@Configuration
public class ComfyuiConfig {





    @Bean
    public ComfyuiApi comfyuiApi() {

        //开启拦截日志（retrofit接口调用时拦截，控制台输出日志）
        //拦截请求的过程和响应的过程
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(30,TimeUnit.SECONDS)//连接超时时间 30s
                .addInterceptor(loggingInterceptor)
            .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://127.0.0.1:8188")
                .addConverterFactory(JacksonConverterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit.create(ComfyuiApi.class);
    }

    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler) {
        WebSocketClient webSocketClient = new StandardWebSocketClient();
        String url = "ws://localhost:8188/ws?clientId=star-graph";
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(webSocketClient, comfyuiMessageHandler, url);
        webSocketConnectionManager.setAutoStartup(true);//
        return webSocketConnectionManager;
    }
}
